<?php
//include COMPONENT_ROOT.'models/bookings.php';
require_once 'includes/ccval.php';

//global $units, $managers;
$units_obj = new Unit();
$customers_obj = new Customer();
$managers = $customers_obj->find(array("user_type" => "manager"));
$bookings_obj = new Booking();
$set_letters_obj = new SetLetters();

function show_bookings(){
	global $units_obj, $KToolBar;
	$units = $units_obj->find("all");
	$limit = $_GET['limit'];

	$bookings_obj = new Booking();
	$query = "SELECT * FROM `".$bookings_obj->get_table_name()."` ORDER BY `booked_on` DESC";
	$paginate = paginate($bookings_obj, $query, $_GET['pg_no'], $limit);
	$bookings = $paginate['obj'];
//	$bookings = $bookings_obj->select_row_query($query, "");
	
	include_once 'views/bookings.html.php';
}

function filter_bookings(){
	global $units_obj, $customers_obj, $KToolBar;
	$bookings = new Booking();
	$units = $units_obj->find("all");
	$sql =  "SELECT * FROM `".Config::table_prefix()."bookings` WHERE ".
			($_POST['unit_address'] != "" ? "`uid` = '".$_POST['unit_address']."' AND ":"").
			(!empty($_POST['arr_date'])? "`startdate` = '".get_date_from_str($_POST['arr_date'])."' AND ":"").
			(!empty($_POST['dep_date'])? "`enddate` = '".get_date_from_str($_POST['dep_date'])."' AND ":"").
			(!empty($_POST['booked_on'])? "`timestamp` = '".substr($_POST['booked_on'], 0, 10)."' AND ":"").
			(!empty($_POST['confirmed'])? "`confirmed` = '".$_POST['confirmed']."' AND ":"").
			(!empty($_POST['booking_reference'])? "`id` = '".$_POST['booking_reference']."' AND ":"").
			(!empty($_POST['unit_manager'])? "`uid` IN (SELECT `id` FROM `".$units_obj->get_table_name()."` WHERE `owner_id` = '".$_POST['unit_manager']."') AND ":"").
			(!empty($_POST['surname'])? "`cid` IN (SELECT `id` FROM `".$customers_obj->get_table_name()."` WHERE `surname` LIKE '%".$_POST['surname']."%') AND ":"").
			($_POST['deposit_paid'] != "" ? "`total_paid` != 0 AND " :"").
			($_POST['paid'] != "" ? "`total_paid` != `total_price` AND " :"").
			($_POST['sd_received'] != "" ? "`security_deposit_received_number` != '' AND " : "").
			($_POST['sd_returned'] != "" ? "`security_deposit_returned_number` != '' AND " :"");
	if(substr($sql, -4, 3) == "AND") $sql = substr($sql, 0, -5);
	else $sql = substr($sql, 0, -7);
	$sql .= " ORDER BY `booked_on` DESC";
	
	$limit = $_POST['limit'];
//	$sql .= " LIMIT 0, $limit";
	$paginate = paginate($bookings, $sql, $_GET['pg_no'], $limit);
	$bookings = $paginate['obj'];
//	$bookings = $bookings->select_row_query($sql, "");
	
	include_once 'views/bookings.html.php';
}

function new_booking(){
	global $KToolBar;
	$units = new Unit();
	$units = $units->find(array("subitem_of" => "0"));
	
	include_once 'views/bookings_new.html.php';
}

function save_booking(){
	global $bookings_obj,$customers_obj,$units_obj,$notice;
	$notice['error'] = 1;
	
	$config = new GeneralConfig();
	$config = $config->find(1);
	
	if(empty($_POST['booking']['uid'])){
		$notice['msg'] = "Please select an unit to proceed";
	}
	else if(empty($_POST['booking']['startdate']) OR empty($_POST['booking']['enddate'])){
		$notice['msg'] = "Please mention a start date and an end date for booking";
	}
	else if( dateDiff("/", $_POST['booking']['enddate'], $_POST['booking']['startdate']) < $config->minimum_stay){
		$notice['msg'] = "You cannot book an unit for less than ".$config->minimum_stay." days of stay.";
	}
	else if(!filter_var($_POST['customer']['email'], FILTER_VALIDATE_EMAIL)){
		$notice['msg'] = "Please enter a valid Email address";
	}
	else{
		$prices_obj = new Price();
		$intervals = $prices_obj->find(array("uid"=>$_POST['booking']['uid']));
		$price = get_price( $_POST['booking']['startdate'], $_POST['booking']['enddate'], $intervals);
		
		$unit = $units_obj->select_row_query("SELECT `clean_fees` FROM `".$units_obj->get_table_name()."` WHERE `id` = '".$_POST['booking']['uid']."'", 1);
		if($no_of_days_stayed < Config::limiting_stay) $clean_fees = (Config::limiting_stay - $no_of_days_stayed) * $unit->clean_fees;
		$_POST['booking']['total_price'] = $price + $clean_fees;
		
		mysql_query("BEGIN");
		$customer_save_msg = $customers_obj->insert_or_update($_POST['customer'], "");
		
		$_POST['booking']['cid'] = mysql_insert_id();
		$_POST['booking']['startdate'] = get_date_from_str($_POST['booking']['startdate']);
		$_POST['booking']['enddate'] = get_date_from_str($_POST['booking']['enddate']);
		$_POST['booking']['booked_on'] = date("Y-m-d");
		$bookings_save_msg = $bookings_obj->insert_or_update($_POST['booking'], "");
		
		if($customer_save_msg['error'] == 0 && $bookings_save_msg['error'] == 0){
			mysql_query("COMMIT");
			$notice['error'] = 0;
			$notice['msg'] = "A new booking was successfully created. Now you can <a href=\"?option=".COMPONENT_NAME."&page=bookings&action=edit&bid=".mysql_insert_id()."\">edit</a> the booking information";
		}
		else {
			$notice['msg'] = $customer_save_msg['msg'];
			mysql_query("ROLLBACK");
		}
	}
}

function show_edit_booking($id){
	//if(!$id) exit;
	global $units_obj, $set_letters_obj, $KToolBar;
	$units = $units_obj->find("all");
	
	$bookings = new Booking();
	$bookings = $bookings->find((int)$id);
	$total_price = $bookings->total_price;
	$subtotal = $total_price*0.2 + $total_price*0.04 + $total_price*0.15;
	
	$payments = new Payment();
	//$sql = 
	$payments = $payments->select_row_query("SELECT * FROM `".$payments->get_table_name()."` WHERE `bid` = '".$bookings->id."'", "");
	
	$cc_info = new CCinfo();
	$cc_info = $cc_info->select_row_query("SELECT * FROM `".$cc_info->get_table_name()."` WHERE `bid` = '".$bookings->id."' AND `active` = 1", 1);
	
	$customers = new Customer();
	//$guest = $customers->find((int)$bookings->cid);
	//$owner = $customers->select_row_query("SELECT `id` FROM `".$customers->get_table_name()."` WHERE `id` = (SELECT `owner_id` FROM `".$units_obj->get_table_name()."` WHERE `id` = '$bookings->uid')", 1);
	$adults = $bookings->adults_info;
	$adults = explode(";",$adults);
	$children = $bookings->children_info;
	$children = explode(";",$children);
	
	$letters = $set_letters_obj->select_row_query("SELECT * FROM `".$set_letters_obj->get_table_name()."` ORDER BY `id` ASC", "");
	
	include_once 'views/booking_edit.html.php';
}

function save_edit_booking($bid){
	global $notice;
	$notice['error'] = 1;
	
	if( CCVal($_POST['cc_info']['number']) ){
		$notice['error'] = 1;
		mysql_query("BEGIN");
		
		/** coverts adults and children array to appropriate string format **/
		$_POST['adults']['name'] = array_filter($_POST['adults']['name']);
		$_POST['adults']['age'] = array_filter($_POST['adults']['age']);
		$_POST['children']['name'] = array_filter($_POST['children']['name']);
		$_POST['children']['age'] = array_filter($_POST['children']['age']);
		
		foreach($_POST['adults']['name'] as $key=>$value){
			$adults_info .= $_POST['adults']['name'][$key].",".$_POST['adults']['age'][$key].";";
		}
		foreach($_POST['children']['name'] as $key=>$value){
			$children_info .= $_POST['children']['name'][$key].",".$_POST['children']['age'][$key].";";
		}
		
		$adults_info = substr($adults_info, 0, -1);
		$children_info = substr($children_info, 0, -1);
		/***/
		
		/** adds the above output to bookings array **/
		$_POST['bookings']['adults_info'] = $adults_info;
		$_POST['bookings']['children_info'] = $children_info;
		unset($_POST['adults'], $_POST['children']);
		/***/
		
		/** change format of the arrival and departure dates **/
		$_POST['bookings']['startdate'] = get_date_from_str($_POST['bookings']['startdate']);
		$_POST['bookings']['enddate'] = get_date_from_str($_POST['bookings']['enddate']);
		/***/
		
		$_POST['payment_date'] = array_filter($_POST['payment_date']);
		$_POST['payment_amount'] = array_filter($_POST['payment_amount']);
	
		$payments = new Payment();
		$no_of_payments = $payments->count("SELECT * FROM `".$payments->get_table_name()."` WHERE `bid` = '".$bid."'");
		if( count($_POST['payment_date']) > $no_of_payments ){
			$date = end($_POST['payment_date']);
			$payment_update_msg = $payments->insert_row_query("INSERT INTO `".$payments->get_table_name()."` (`bid`, `date`, `method`, `amount`) VALUES('$bid','".$date."','cc','".end($_POST['payment_amount'])."')");
		}
		$payment = $payments->select_row_query("SELECT SUM(amount) AS sum FROM `".$payments->get_table_name()."` WHERE `bid` = '$bid'", 1);
		$_POST['bookings']['total_paid'] = $payment->sum;
		$bookings = new Booking();
		$bookings_update_msg = $bookings->insert_or_update($_POST['bookings'], array('id'=>$bid));
		$customers = new Customer();
		$customers_update_msg = $customers->insert_or_update($_POST['customer'], array('id'=>$_POST['bookings']['cid']));
		$cc_info = new CCinfo();
		$cc_info_update_msg = $cc_info->insert_or_update($_POST['cc_info'], array('bid'=>$bid, 'active'=>1));
		
		//echo $payment_update_msg."<br />".$bookings_update_msg."<br />".$customers_update_msg."<br />".$cc_info_update_msg."<br />";
		
		/** if all sql excuted successfully do commit else rollback **/
		if($payment_update_msg['error'] == 0 && $bookings_update_msg['error'] == 0 && $customers_update_msg['error'] == 0 && $cc_info_update_msg['error'] == 0){
			mysql_query("COMMIT");
			$notice['error'] = 0;
			$notice['msg'] = "The booking information has been updated";
		}
		else{
			mysql_query("ROLLBACK");
			$notice['msg'] = "Booking information cannot be updated. Please try again later.";
		}
	}
	else{
		$notice['msg'] = "Please ensure that you have entered a valid credit card number.";
	}
	/***/
}

function delete_selected_bookings(){
	global $bookings_obj, $notice;
	$notice['error'] = 1;
	
	$notice = delete_selected_items($_POST['bookings'], $bookings_obj);
	if($notice['error'] == 0) $notice['msg'] = "The selected bookings have been deleted";
	else if($notice['error'] == 1) $notice['msg'] = "Some Error occured while deleting. Please try again later.";
}

function set_items_confirmed(){
	global $bookings_obj;
	$msg = confirm_selected_items($_POST['bookings'], $bookings_obj, $_POST['set_confirmed']);
}
?>